package com.blog.controller.user;

import com.blog.entity.User;
import com.blog.enums.StaticVariable;
import com.blog.service.UserService;
import com.blog.util.FileCopyUtil;
import com.blog.util.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Api(tags = "用户信息修改")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;

	@ApiOperation("跳转个人中心")
	@GetMapping("/user")
	public ModelAndView getUser(ModelAndView modelAndView,HttpSession session){
		User user = (User) session.getAttribute("user");
		modelAndView.addObject("user",user);
		modelAndView.setViewName("user/user.html");
		return modelAndView;
	}

	@ApiOperation("跳转个人中心修改页面")
	@GetMapping("/updateUser")
	public ModelAndView updateUser(ModelAndView modelAndView,HttpSession session){
		User user = (User) session.getAttribute("user");
		modelAndView.addObject("user",user);
		modelAndView.setViewName("user/user-input.html");
		return modelAndView;
	}

	@ApiOperation("修改用户信息")
	@PostMapping("/updateUserInfo")
	public ModelAndView imageUpload(ModelAndView modelAndView, @RequestParam("file") MultipartFile file,
									@RequestParam("username") String username,@RequestParam("password") String password,
									HttpSession session,HttpServletRequest request, HttpServletResponse response) {
		User user = (User) session.getAttribute("user");

		try {
			request.setCharacterEncoding("utf-8");
			response.setHeader("Content-Type", "application/json");

			File targetFile = null;
			String avatar = "";
			String fileName = file.getOriginalFilename();
			StringBuilder stringBuilder = new StringBuilder();

			if (StringUtils.isNotBlank(fileName)) {
				/**
				 * 图片访问的URI-不带端口号
				 * request.getScheme()：协议http/https
				 * request.getServerName()：IP-服务器名
				 * request.getServerPort()：端口
				 * request.getContextPath()：当前页面所在应用的名字
				 */
				String returnUrl = request.getScheme() + "://" + request.getServerName() + ":"+ request.getServerPort() + request.getContextPath() + StaticVariable.uploadAvatar;
				//文件临时存储位置
				String path = request.getSession().getServletContext().getRealPath("") + "upload" + File.separator + "avatar";
				//文件后缀
				String fileSuffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
				//新的文件名
				fileName = System.currentTimeMillis() + "_" + new Random().nextInt(1000) + fileSuffix;

				//设置日期文件夹
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				String fileAdd = sdf.format(new Date());
				//获取文件夹路径
				path = path + File.separator + fileAdd + File.separator;
				File file1 = new File(path);

				//如果文件夹不存在则创建
				if (!file1.exists() && !file1.isDirectory()) {
					if (!file1.mkdirs()) {
						throw new IOException("文件夹创建失败,路径为：" + file1);
					}
				}
				//将图片存入文件夹
				targetFile = new File(file1, fileName);

				//将上传的文件写到服务器上指定的文件。
				file.transferTo(targetFile);
				String projectPath = System.getProperty("user.dir");
				//文件复制
				String src = path + fileName;
				//根据自己系统的resource 目录所在位置进行自行配置
				String destDir = projectPath + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "static" + File.separator + "upload" + File.separator + "avatar" + File.separator + fileAdd + File.separator;
				FileCopyUtil.copyFile(src, destDir, fileName);

				avatar = StaticVariable.uploadAvatar + fileAdd + "/" + fileName;

				user.setAvatar(avatar);
				stringBuilder.append("头像上传成功");
			}
			if(!StringUtils.isEmpty(username)){
				user.setUsername(username);
				stringBuilder.append(" 昵称修改成功");
			}
			if(!StringUtils.isEmpty(password)){
				user.setPassword(MD5Utils.code(password));
				stringBuilder.append(" 密码修改成功");
			}
			user.setUpdateTime(new Date());

			int res = userService.updateUserInfo(user);

			modelAndView.addObject("message",stringBuilder.toString().trim());
			modelAndView.addObject("user",user);
		} catch (Exception e) {
			modelAndView.addObject("message","修改失败");
			log.info("未上传头像或头像上传失败: "+e.getMessage());
		}

        modelAndView.setViewName("user/user-input.html");
		return modelAndView;
	}

}
